//
//  YFCalendar.m
//  CalendarDemo
//
//  Created by Winny Zhang on 2019/4/1.
//  Copyright © 2019 Winny Zhang. All rights reserved.
//

#import "YFCalendar.h"
#import "YFCalendarCell.h"
#import "NSDate+YFExtension.h"

@interface YFCalendar () <FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance>
/**
 背景 View
 */
@property (weak, nonatomic) IBOutlet UIView *calendarContentView;
/**
 起点标签 Label
 */
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
/**
 终点标签 Label
 */
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
/**
 起点时间 Label
 */
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
/**
 终点时间 Label
 */
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;

/**
 月份 Label
 */
@property (weak, nonatomic) IBOutlet UILabel *monthLabel;
/**
 今天 Button
 */
@property (weak, nonatomic) IBOutlet UIButton *todayButton;
/**
 日历
 */
@property (weak, nonatomic) IBOutlet FSCalendar *calendar;
/**
 确认 按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
/**
 公历
 */
@property (strong, nonatomic) NSCalendar *gregorian;
/**
 日期格式
 */
@property (strong, nonatomic) NSDateFormatter *dateFormatter;

/**
 选中的日期1 NSDate
 */
@property (strong, nonatomic) NSDate *date1;
/**
 选中的日期2 NSDate
 */
@property (strong, nonatomic) NSDate *date2;

/**
 大写月份
 */
@property (strong, nonatomic) NSArray<NSString *> *uperMonths;
/**
 小写月份
 */
@property (strong, nonatomic) NSArray<NSNumber *> *lowerMonths;

/**
 今天 几号
 */
@property (assign, nonatomic) NSInteger today;


/**
 保存 Block
 */
@property (copy, nonatomic) void(^completion)(NSString *startDate, NSString *endDate);




@end

@implementation YFCalendar

+ (instancetype)showWithCompletion:(void(^)(NSString *startDate, NSString *endDate))completion {
    YFCalendar *calendar = [[NSBundle mainBundle] loadNibNamed:@"YFCalendar" owner:nil options:nil].firstObject;
    calendar.frame = [UIScreen mainScreen].bounds;
    calendar.completion = [completion copy];
    [calendar show];
    return calendar;
}

- (void)show {
    self.alpha = 0;
    self.calendarContentView.transform = CGAffineTransformMakeScale(0, 0);
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
        self.alpha = 1;
        self.calendarContentView.transform = CGAffineTransformMakeScale(1.7, 1.7);
        self.calendarContentView.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        self.calendarContentView.transform = CGAffineTransformIdentity;
    }];
}

- (void)dismiss {
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
        self.alpha = 0;
        self.calendarContentView.transform = CGAffineTransformMakeScale(0, 0);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self.alpha = 1;
        self.calendarContentView.transform = CGAffineTransformIdentity;
    }];
}


- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupSubViews];
    [self initProperties];
    [self setupCalendar];
    self.uperMonths = @[@"一", @"二", @"三", @"四", @"五", @"六", @"七", @"八", @"九", @"十", @"十一", @"十二"];
    self.lowerMonths = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12];
}

- (void)initProperties {
    self.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy-MM-dd";
}

- (void)setupCalendar {
    self.calendar.headerHeight = 0;
    self.calendar.weekdayHeight = 0;
    self.calendar.swipeToChooseGesture.enabled = YES;
    self.calendar.today = nil;
    self.calendar.dataSource = self;
    self.calendar.delegate = self;
    self.calendar.placeholderType = FSCalendarPlaceholderTypeFillSixRows;
    [self.calendar registerClass:[YFCalendarCell class] forCellReuseIdentifier:@"YFCalendarCell"];
    
    self.today = [NSDate date].currentDay;
    [self.todayButton setTitle:[NSString stringWithFormat:@"%zd", self.today] forState:(UIControlStateNormal)];
    self.startTimeLabel.text = @"----------";
    self.endTimeLabel.text = @"----------";
}

- (void)setupSubViews {
    
    self.calendarContentView.layer.masksToBounds = YES;
    self.calendarContentView.layer.cornerRadius = 5;
    
    self.startLabel.layer.masksToBounds = YES;
    self.startLabel.layer.cornerRadius = self.startLabel.frame.size.height * 0.5;
    self.endLabel.layer.masksToBounds = YES;
    self.endLabel.layer.cornerRadius = self.endLabel.frame.size.height * 0.5;
    
    [self.confirmButton setBackgroundImage:UIColor.blackColor.image forState:(UIControlStateNormal)];
    [self.confirmButton rounded:(UIRectCornerAllCorners) radius:5];
}

#pragma mark - FSCalendarDataSource
- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar {
    return [NSDate date];
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar {
    return [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:12 toDate:[NSDate date] options:0];
}

//- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date {
//    if ([self.gregorian isDateInToday:date]) return @"今";
//    return nil;
//}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    YFCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"YFCalendarCell" forDate:date atMonthPosition:monthPosition];
    return cell;
}

- (void)calendar:(FSCalendar *)calendar willDisplayCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition: (FSCalendarMonthPosition)monthPosition {
    [self configureCell:cell forDate:date atMonthPosition:monthPosition];
}

#pragma mark - FSCalendarDelegate

- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    return monthPosition == FSCalendarMonthPositionCurrent;
}

- (BOOL)calendar:(FSCalendar *)calendar shouldDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    return YES;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    
    // 处理复选
    if ([date isEqualToDate:self.date1] || [date isEqualToDate:self.date2]) {
        self.date1 = nil;
        self.date2 = nil;
    }
    
    if (calendar.swipeToChooseGesture.state == UIGestureRecognizerStateChanged) {
        
        if (!self.date1) {
            self.date1 = date;
        } else {
            if (self.date2) {
                [calendar deselectDate:self.date2];
            }
            self.date2 = date;
        }
    } else {
        if (self.date2) {
            [calendar deselectDate:self.date1];
            [calendar deselectDate:self.date2];
            self.date1 = date;
            self.date2 = nil;
        } else if (!self.date1) {
            self.date1 = date;
        } else {
            self.date2 = date;
        }
    }
    
    if (self.date1 && self.date2) {
        // firstDate  is in the future
        if ([self.date1 compare:self.date2] == NSOrderedDescending) {
            self.startTimeLabel.text = [self.dateFormatter stringFromDate:self.date2];
            self.endTimeLabel.text = [self.dateFormatter stringFromDate:self.date1];
        } else {
            self.startTimeLabel.text = [self.dateFormatter stringFromDate:self.date1];
            self.endTimeLabel.text = [self.dateFormatter stringFromDate:self.date2];
        }
    } else if (!self.date1 && !self.date2){
        self.startTimeLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];
        self.endTimeLabel.text = @"----------";
    } else {
        self.startTimeLabel.text = [self.dateFormatter stringFromDate:self.date1];
        self.endTimeLabel.text = @"----------";
    }
    
    [self configureVisibleCells];
}

- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    [self configureVisibleCells];
}

- (NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date {
    if ([self.gregorian isDateInToday:date]) {
        return @[[UIColor orangeColor]];
    }
    return @[appearance.eventDefaultColor];
}


#pragma mark - Private methods

- (void)configureVisibleCells {
    [self.calendar.visibleCells enumerateObjectsUsingBlock:^(__kindof FSCalendarCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDate *date = [self.calendar dateForCell:obj];
        FSCalendarMonthPosition position = [self.calendar monthPositionForCell:obj];
        [self configureCell:obj forDate:date atMonthPosition:position];
    }];
}

- (void)configureCell:(__kindof FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position {
    
    self.monthLabel.text = [NSString stringWithFormat:@"%@月", [self uperMonthString:self.calendar.currentPage.currentMonth]];
    
    YFCalendarCell *rangeCell = cell;
    rangeCell.selectionLayer.hidden = YES;
    
    if ((self.date1 && self.date2 && [date isBetweenDate:self.date1 andDate:self.date2]) || [date isEqualToDate:self.date1] || [date isEqualToDate:self.date2]) {
        rangeCell.selectionLayer.hidden = NO;
        rangeCell.titleLabel.textColor = [UIColor whiteColor];
    } else {
        rangeCell.selectionLayer.hidden = YES;
        if (rangeCell.isPlaceholder) {
            rangeCell.titleLabel.textColor = [UIColor lightGrayColor];
        } else {
            if (date.currentDay == self.today) {
                rangeCell.titleLabel.textColor = [UIColor whiteColor];
            } else {
                rangeCell.titleLabel.textColor = [UIColor blackColor];
            }
        }
    }
    
    SelectionType selectionType = SelectionTypeNone;
    if (self.date1 && self.date2) {
         // firstDate  is in the future
        if ([self.date1 compare:self.date2] == NSOrderedDescending) {
            
            if ([date isEqualToDate:self.date1]) {
                
                selectionType = SelectionTypeRightBorder;
                
            } else if ([date isEqualToDate:self.date2]) {
                
                selectionType = SelectionTypeLeftBorder;
                
            } else if ((![date isEqualToDate:self.date1]) &&
                       (![date isEqualToDate:self.date2]) &&
                       [date isBetweenDate:self.date1 andDate:self.date2]) {
                
                selectionType = SelectionTypeMiddle;
            }
        } else {
            
            if ([date isEqualToDate:self.date1]) {
                
                selectionType = SelectionTypeLeftBorder;
                
            } else if ([date isEqualToDate:self.date2]) {
                
                selectionType = SelectionTypeRightBorder;
                
            } else if ((![date isEqualToDate:self.date1]) &&
                       (![date isEqualToDate:self.date2]) &&
                       [date isBetweenDate:self.date1 andDate:self.date2]) {
                
                selectionType = SelectionTypeMiddle;
            }
            
        }
    } else if ((self.date1 && self.date2 == nil) || (self.date1 == nil && self.date2)) {
        
        if ([date isEqualToDate:self.date1] || [date isEqualToDate:self.date2]) {
            selectionType = SelectionTypeSingle;
        }
    }
    rangeCell.selectionType = selectionType;
    
    rangeCell.todayLayer.hidden = !((self.today == date.currentDay) && (!rangeCell.isPlaceholder));
}


#pragma 获取当前月份转换为大写月份
- (NSString *)uperMonthString:(NSInteger)month {
    __block NSUInteger index = 0;
    __block NSString *monthString = @"";
    [self.lowerMonths enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (month == obj.integerValue) {
            index = idx;
        }
    }];
    [self.uperMonths enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (index == idx) {
            monthString = obj;
        }
    }];
    return monthString;
}

#pragma mark - 按钮点击事件
- (IBAction)confirmButtonClick:(id)sender {
    
    if (self.date1 && self.date2 && _completion) {
        [self dismiss];
        _completion(_startTimeLabel.text, _endTimeLabel.text);
    }
}
- (IBAction)dismissButtonClicked:(id)sender {
    [self dismiss];
}


@end
